package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/31 20:16
 */
@Service
@Slf4j
public class WorkSpaceServiceImpl implements WorkSpaceService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DishMapper dishMapper;
    @Resource
    private SetmealMapper setmealMapper;

    /**
     * 查询今日运营数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        // 订单总数
        Integer totalOrderCount = orderMapper.getOrderCount(map);
        if (totalOrderCount == null) {
            totalOrderCount = 0;
        }
        map.put("status", Orders.COMPLETED);
        // 营业额
        Double turnover = orderMapper.getAmount(map);
        if (turnover == null) {
            turnover = 0.0;
        }
        // 有效订单数
        Integer validOrderCount = orderMapper.getOrderCount(map);
        if (validOrderCount == null) {
            validOrderCount = 0;
        }
        // 订单完成率
        Double orderCompletionRate = Double.valueOf(validOrderCount) / totalOrderCount;
        if (totalOrderCount == 0 || orderCompletionRate == null) {
            orderCompletionRate = 0.0;
        }
        // 平均客单价
        Double unitPrice = turnover / validOrderCount;
        if (validOrderCount == 0 || unitPrice == null) {
            unitPrice = 0.0;
        }
        // 新增用户数量
        Integer newUsers = userMapper.getUserNumber(map);
        if (newUsers == null) {
            newUsers = 0;
        }
        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }

    /**
     * 工作台查看订单管理数据
     *
     * @return
     */
    @Override
    public OrderOverViewVO overviewOrders() {
        Map map = new HashMap();
        // 全部订单
        Integer allOrders = orderMapper.getOrderCount(map);
        // 已取消订单
        map.put("status", Orders.CANCELLED);
        Integer cancelledOrders = orderMapper.getOrderCount(map);
        // 已完成数量
        map.put("status", Orders.COMPLETED);
        Integer completedOrders = orderMapper.getOrderCount(map);
        // 待派送数量
        map.put("status", Orders.CONFIRMED);
        Integer deliveredOrders = orderMapper.getOrderCount(map);
        // 待接单
        map.put("status", Orders.TO_BE_CONFIRMED);
        Integer waitingOrders = orderMapper.getOrderCount(map);
        return OrderOverViewVO.builder()
                .allOrders(allOrders)
                .cancelledOrders(cancelledOrders)
                .completedOrders(completedOrders)
                .deliveredOrders(deliveredOrders)
                .waitingOrders(waitingOrders)
                .build();
    }

    /**
     * 工作台查看菜品总览数据
     *
     * @return
     */
    @Override
    public DishOverViewVO dishOverView() {
        // 起售菜品数量
        Integer sold = dishMapper.dishCountByStatus(StatusConstant.ENABLE);
        // 停售菜品数量
        Integer discontinued = dishMapper.dishCountByStatus(StatusConstant.DISABLE);
        return DishOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 工作台查看套餐总览数据
     *
     * @return
     */
    @Override
    public SetmealOverViewVO overviewSetmeals() {
        Integer sold = setmealMapper.setmealCountByStatus(StatusConstant.ENABLE);
        Integer discontinued = setmealMapper.setmealCountByStatus(StatusConstant.DISABLE);
        return SetmealOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 导出excel报表
     *
     * @param response
     */
    @Override
    public void exportExcel(HttpServletResponse response) {
        // 获取今日日期
        LocalDate today = LocalDate.now();
        // 获取开始日期
        LocalDate begin = today.minusDays(30);
        // 获取结束日期
        LocalDate end = today.minusDays(1);
        try {
            // 读取类加载路径下的excel现有模板
            XSSFWorkbook excel = new XSSFWorkbook(this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx"));
            // 获取sheet
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 给第二行第二列赋值
            sheet.getRow(1).getCell(1).setCellValue("报表日期：" + begin + "至" + end);
            // 调用getBusinessData方法查询数据库近三十日的数据总览
            BusinessDataVO totalBusinessData = getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
            // 给概览数据赋值
            sheet.getRow(3).getCell(2).setCellValue(totalBusinessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(totalBusinessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(totalBusinessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(totalBusinessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(totalBusinessData.getUnitPrice());
            // 遍历30天，给明细数据赋值
            LocalDate date = begin.plusDays(-1);
            for (int i = 0; i < 30; i++) {
                date = date.plusDays(1);
                BusinessDataVO todayData = getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                sheet.getRow(7 + i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7 + i).getCell(2).setCellValue(todayData.getTurnover());
                sheet.getRow(7 + i).getCell(3).setCellValue(todayData.getValidOrderCount());
                sheet.getRow(7 + i).getCell(4).setCellValue(todayData.getOrderCompletionRate());
                sheet.getRow(7 + i).getCell(5).setCellValue(todayData.getUnitPrice());
                sheet.getRow(7 + i).getCell(6).setCellValue(todayData.getNewUsers());
            }
            // 获取响应给前端的输出流对象
            ServletOutputStream outputStream = response.getOutputStream();
            // 将该excel写入到该输出流对象
            excel.write(outputStream);
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
